#include <stdio.h>

/**
 * 以下代码的运行结果是什么样子呢？

Pick an integer from 1 to 100. I will try to guess it.
Respond with a y if my guess is right and with
an n if it is wrong.
Uh...is your number 1?
n
Well, then, is it 2?
Well, then, is it 3?
n
Well, then, is it 4?
Well, then, is it 5?
y
I knew I could do it!

 * 注意，为什么输入n以后是跳两格而不是一格？


 * 坑的地方就在这里，当输入n回车以后，实际上产生了2个字符，一个是n一个是enter
 * 他们都不等于y，所以while里面的语句运行了2次。

 * 该怎么来解决这个问题呢？
 * 换成right_func即可。
*/

void err_func();

void right_func();

int main(void)
{
    err_func();
    return 0;
}

void err_func()
{
    int guess = 1;
    int response;
    printf("Pick an integer from 1 to 100. I will try to guess ");
    printf("it.\nRespond with a y if my guess is right and with");
    printf("\nan n if it is wrong.\n");
    printf("Uh...is your number %d?\n", guess);
    while (getchar() != 'y') /* 获取响应，与 y 做对比 */
    {
        printf("Well, then, is it %d?\n", ++guess);
        while ((response = getchar()) != '\n')
            continue; /* 跳过剩余的输入行 */
    }
    printf("I knew I could do it!\n");
}

void right_func()
{
    int guess = 1;
    int response;
    printf("Pick an integer from 1 to 100. I will try to guess ");
    printf("it.\nRespond with a y if my guess is right and with");
    printf("\nan n if it is wrong.\n");
    printf("Uh...is your number %d?\n", guess);
    // while (getchar() != 'y') /* 获取响应，与 y 做对比 */
    //     printf("Well, then, is it %d?\n", ++guess);
    while ((response = getchar()) != 'y') /* 获取响应 */
    {
        if (response == 'n')
            printf("Well, then, is it %d?\n", ++guess);
        else
            printf("Sorry, I understand only y or n.\n");
        // 跳过除去y和n以外的其他字符，包括回车
        while ((response = getchar()) != '\n')
            continue; /* 跳过剩余的输入行 */
    }
    printf("I knew I could do it!\n");
}